package com.videri.match.client;

import com.allen_sauer.gwt.dragdrop.client.PickupDragController;
import com.allen_sauer.gwt.dragdrop.client.drop.NoOverlapDropController;
import com.allen_sauer.gwt.dragdrop.client.util.DOMUtil;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.HorizontalSplitPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBoxBase;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.VerticalSplitPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
import com.videri.match.client.MatchSink.MatchSinkInfo;

public class SRMRoom extends MatchSink {
	private AbsolutePanel myAbsolutePanel = new AbsolutePanel();
	VerticalPanel srmTopLevel = new VerticalPanel();
	HorizontalPanel srmToolbar = new HorizontalPanel();
	HorizontalPanel srmBottomStuff = new HorizontalPanel();
	VerticalPanel srmSidebar = new VerticalPanel();
	VerticalSplitPanel srmChatAreas = new VerticalSplitPanel();
	ScrollPanel chathistory = new ScrollPanel();
	TextArea chattype = new TextArea();
	String chathistorytext;
	final VideriChatServiceAsync chatService;
	ServiceDefTarget endpoint;
	String[] privateMessageHandles;
	
	public static MatchSinkInfo init(){
		return new MatchSinkInfo("Single Round Match") {
			public MatchSink createInstance(){
				return new SRMRoom("Home");
			}

			public String getColor(){
				// You can change this to change the color of the tab for this option
				return "#F19928";
			}
		};
	}

	public SRMRoom(final String room)
	{
		  chatService = (VideriChatServiceAsync)GWT.create(VideriChatService.class);
		  endpoint = (ServiceDefTarget) chatService;
		  String moduleRelativeURL = GWT.getModuleBaseURL()+"chat";
		  endpoint.setServiceEntryPoint(moduleRelativeURL);
		  privateMessageHandles = new String[0];
		
		final AsyncCallback joinRoomCallback = new AsyncCallback() {                
			public void onSuccess(Object result) {
				boolean res = ((Boolean) result).booleanValue();
				if(!res)
					chathistorytext = new String("<b>Error joining room!</b>");
				else
					chathistorytext = new String("<b>Welcome to "+room+"!</b>");
			}                
			public void onFailure(Throwable caught) {  
				chathistorytext = new String("<b>Error: Couldn't Reach Server!</b>");
			}            
		};
		
		chatService.joinRoom(VideriMatchSink.cookie, room, joinRoomCallback);
		//initWidget(srmTopLevel);
		//if(user.length() == 0) //Not logged in
		//	return;
		//initialize(user, room);
		
			    final VerticalPanel vert = new VerticalPanel();
			    vert.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
			    vert.setSpacing(8);
			    vert.add(makeLabel(room+" Users:"));
			    
				final AsyncCallback getUserListCallback = new AsyncCallback() {                
					public void onSuccess(Object result) {
						final String[] res = (String[]) result;
						System.out.println("getUserListSucceeded.");
						if(res == null)
							System.out.println("getUserList returned null.");
						if(res == null || res.length == 0)
							return;
						System.out.println("getUserList length:"+res.length);
						vert.clear();
						for(int i = 0; i < res.length; i++)
						{
							final int count = i;
							Button b = new Button(res[i]);
							b.addClickListener(new ClickListener() {
								public void onClick(Widget sender) {
									for(int k = 0; k < privateMessageHandles.length; k++)
									{
										if(privateMessageHandles[k].equals(res[count])) //Remove
										{
											String[] privateMessageHandles2 = new String[privateMessageHandles.length - 1];
											for(int j = 0; j < k; j++)
												privateMessageHandles2[j] = privateMessageHandles[j];
											for(int j = k+1; j < privateMessageHandles.length; j++)
												privateMessageHandles2[j-1] = privateMessageHandles[j];
											privateMessageHandles = privateMessageHandles2;
										}
										return;
									}
									String[] privateMessageHandles2 = new String[privateMessageHandles.length + 1];
									for(int j = 0; j < privateMessageHandles.length; j++)
										privateMessageHandles2[j] = privateMessageHandles[j];
									privateMessageHandles2[privateMessageHandles.length] = res[count];
								}
							});
							vert.add(b);
						}
							
					}                
					public void onFailure(Throwable caught) {
						System.out.println("getUserList() Failed!");
					}            
				};
				
				Timer getUserListTimer = new Timer() {
					public void run()
					{
						chatService.getUserList(VideriMatchSink.cookie, room, getUserListCallback);
					}
				};
				getUserListTimer.scheduleRepeating(1000);

			    TabPanel tabs = new TabPanel();
			    tabs.add(vert, room+" User List");
			    //tabs.add(dock, "Dock Panel");
			    tabs.setWidth("100%");
			    tabs.selectTab(0);

			    VerticalPanel vSplit = new VerticalPanel();
			    chathistory = new ScrollPanel(new HTML(chathistorytext));
			    
			    chathistory.setAlwaysShowScrollBars(true);
			    chathistory.setWidth("100%");
			    chathistory.setHeight("350px");
			    
			  //Set up automatically-refreshing text chat area
				
				
				  
				  
				final AsyncCallback getMessagesCallback = new AsyncCallback() {                
					public void onSuccess(Object result) {
						if(result == null)
						{
							System.out.println("No Messages");
							return;
						}
						ChatMessageList cml = (ChatMessageList) result;
						for(int i = 0; i < cml.messages.length; i++)
						{
							chathistorytext = chathistorytext+"<br><b>"+cml.usernames[i];
							if(cml.isPrivate[i])
								chathistorytext = chathistorytext+" (private)";
							chathistorytext = chathistorytext+":</b> "+cml.messages[i].replaceAll("\n", "<br>")+"";
						}
						chathistory.clear();
						chathistory.add(new HTML(chathistorytext));
					}                
					public void onFailure(Throwable caught) {                                 
					}            
				};
				Timer chatRefreshTimer = new Timer() {
					public void run() {
						chatService.getMessages(VideriMatchSink.cookie, getMessagesCallback);
					}
				};
				chatRefreshTimer.scheduleRepeating(500);
			    
			    chattype = new TextArea();
			    chattype.setWidth("100%");
			    chattype.setCharacterWidth(50);
			    chattype.setVisibleLines(3);
			    
			    
				final AsyncCallback addMessageCallback = new AsyncCallback() {                
					public void onSuccess(Object result) {
						String res = (String) result;
						if(res.length() != 0)
						{
							chathistorytext = chathistorytext+"<br>"+res;
							chathistory.clear();
							chathistory.add(new HTML(chathistorytext));
						}
					}                
					public void onFailure(Throwable caught) {    
						chathistorytext = chathistorytext+"<br>"+"<b>Error communicating with server!</b>";
						chathistory.clear();
						chathistory.add(new HTML(chathistorytext));						
					}            
				};
			    
			    chattype.addKeyboardListener(new KeyboardListenerAdapter() {
			    	public void onKeyPress(Widget sender, char keyCode, int modifiers) {
			    		if(sender == chattype)
			    		{
			    			if(keyCode == (char) KeyboardListenerAdapter.KEY_ENTER && modifiers == 0)
			    			{
								chathistorytext = chathistorytext+"<br><b>You:</b> "+chattype.getText().replaceAll("\n", "<br>");
								chathistory.clear();
								chathistory.add(new HTML(chathistorytext));
			    				chatService.addMessage(VideriMatchSink.cookie, chattype.getText(), privateMessageHandles, addMessageCallback);
			    				privateMessageHandles = new String[0];
			    				chattype.cancelKey();
			    				chattype.setText("");	
			    				chattype.setCursorPos(0);
			    			}
			    		}
			    	}
			    });
			    
			    vSplit.add(chathistory);
			    vSplit.add(chattype);
			    
			    HorizontalSplitPanel hSplit = new HorizontalSplitPanel();
			    hSplit.setLeftWidget(tabs);
			    hSplit.setRightWidget(vSplit);
			    
			    initWidget(hSplit);
			    hSplit.setSize("100%", "700px");
		
				}	

	private Widget createTextThing(final TextBoxBase textBox, boolean addSelection) {
	    HorizontalPanel p = new HorizontalPanel();
	    p.setSpacing(4);

	    p.add(textBox);

	    if (addSelection) {
	      final HTML echo = new HTML();
	  
	      p.add(echo);
	      textBox.addKeyboardListener(new KeyboardListenerAdapter() {
	        public void onKeyUp(Widget sender, char keyCode, int modifiers) {
	          updateText(textBox, echo);
	        }
	      });
	  
	      textBox.addClickListener(new ClickListener() {
	        public void onClick(Widget sender) {
	          updateText(textBox, echo);
	        }
	      });
	  
	      updateText(textBox, echo);
	    }
	    return p;
	  }

	  private void updateText(TextBoxBase text, HTML echo) {
	    echo.setHTML("Selection: " + text.getCursorPos() + ", "
	        + text.getSelectionLength());
	  }
	
	public void initialize(final String user, final String room){
		System.out.println("SRMRoom is initializing");
		srmToolbar.clear();
		
		HTML htmluser = new HTML(user);
		HTML htmlroom = new HTML(room);
		
		srmToolbar.add(htmluser);
		srmToolbar.add(htmlroom);
		//srmToolbar.setSpacing(5);
		srmToolbar.setCellHorizontalAlignment(htmluser, HorizontalPanel.ALIGN_LEFT);
		srmToolbar.setCellHorizontalAlignment(htmlroom, HorizontalPanel.ALIGN_RIGHT);
		
		HTML html1 = new HTML("Test1");
		HTML html2 = new HTML("Test2");
		srmSidebar.add(html1);
		srmSidebar.add(html2);
		srmSidebar.setCellVerticalAlignment(html1, VerticalPanel.ALIGN_TOP);
		srmSidebar.setCellVerticalAlignment(html2, VerticalPanel.ALIGN_BOTTOM);
		//srmSidebar.setSpacing(5);
		
		
		


		srmTopLevel.add(srmToolbar);
		srmTopLevel.setCellHeight(srmToolbar,"125px");
		srmBottomStuff.add(srmSidebar);
		srmBottomStuff.setCellWidth(srmSidebar,"150px");
		srmToolbar.setBorderWidth(1);
		//srmToolbar.setHeight("10%");
		//srmSidebar.setWidth("20%");
		//srmChatAreas.add
		//Widget chathistory2 = createTextThing(chathistory, false);
		Widget chattype2 = createTextThing(chattype, false);
		srmChatAreas.setTopWidget(chathistory);
		srmChatAreas.setBottomWidget(chattype2);
		srmChatAreas.setSize("100%", "450px");
		//srmChatAreas.setSplitPosition("30em");
		//chathistory.setHeight("65%");
		//chathistory.setWidth("90%");
		//chattype.setWidth("90%");
		
		srmBottomStuff.add(srmChatAreas);
		srmTopLevel.add(srmBottomStuff);
			
		srmTopLevel.setWidth("100%");
		srmTopLevel.setHeight("100%");
		
		initWidget(srmTopLevel);
	}
	
	  private HTML makeLabel(String caption) {
		    HTML html = new HTML(caption);
		    html.setStyleName("ks-layouts-Label");
		    return html;
		  }
	  
	  public void onHide()
	  {
		  chatService.leaveRoom(VideriMatchSink.cookie, new AsyncCallback() {
				public void onSuccess(Object result) {
				}                
				public void onFailure(Throwable caught) {    				
				}     
		  });
		  chathistory.clear();
		  chattype.setText("");
		  chathistorytext = "";
	  }
}
